package com.hwtx.form.plugin;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hwtx.form.annotation.Action;
import com.hwtx.form.annotation.FormType;
import com.hwtx.form.annotation.Log;
import com.hwtx.form.annotation.OperationType;
import com.hwtx.form.domain.def.Select;
import com.hwtx.form.domain.handle.FormDataHandle;
import com.hwtx.form.domain.repo.ApiRepo;
import com.hwtx.form.persistence.entity.ApiDef;
import com.hwtx.form.util.FormUtil;
import com.hwtx.form.util.JacksonUtil;
import com.hwtx.form.util.Param;
import io.geekidea.boot.framework.exception.BusinessException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Map;

@FormType(value = "apiInfo", comment = "api接口相关")
@Slf4j
public class ApiFormDataHandle implements FormDataHandle {

    @Resource
    private ApiRepo apiRepo;
    @Action
    @Log(type = OperationType.GET, value = "获取api参数")
    public Select apiParams(Map<String, Object> formData) {
        Select select = new Select();
        String code = FormUtil.getStrPostValue(formData, "name");
        if (StringUtils.isBlank(code)) {
            throw new BusinessException("name不能为空");
        }
        ApiDef apiDef = apiRepo.getApiDef(code);
        if (apiDef == null) {
            throw new BusinessException("name不存在");
        }
        List<Param> params = JacksonUtil.json2Array(apiDef.getParams(), new TypeReference<>() {
        });
        if (params != null) {
            select.setOptions(params.stream().map(param -> {
                Select.Option option = new Select.Option("#i18n{dict}", "1");
                option.setLabel(param.getName());
                option.setValue(param.getName());
                return option;
            }).toList());
        }
        return select;
    }
}